/**
 * system-config controller
 */

import { factories } from '@strapi/strapi'

export default factories.createCoreController('api::system-config.system-config', ({ strapi }) => ({
  async save(ctx) {
    const authUser = ctx.state.user;
    if (!authUser) {
      return ctx.unauthorized();
    }
    try {
      const body = ctx.request.body as any;
      const data = body?.data;
      const jsonData = JSON.stringify(data);

      const isExist = await strapi.documents("api::system-config.system-config").findFirst({
        filters: {
          user: authUser.id,
        }
      });
      if (isExist) {
        const result = await strapi.documents("api::system-config.system-config").update({
          documentId: isExist.documentId,
          data: {
            config: jsonData,
          },
        });
        return result;
      } else {
        const result = await strapi.documents("api::system-config.system-config").create({
          data: {
            user: authUser.id,
            config: jsonData,
          },
          status: "draft"
        });
        return result;
      }
    } catch (e) {
      return ctx.badRequest();
    }
  },
  async me(ctx) {
    const authUser = ctx.state.user;
    if (!authUser) {
      return ctx.unauthorized();
    }
    const target = await strapi.documents("api::system-config.system-config").findFirst({
      filters: {
        user: authUser.id
      }
    });
    return target ? target : {}
  }
}));
